#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 利用命名空间解析XML文档
问题: 你想解析某个XML文档，文档中使用了XML命名空间。
提示 : 
"""

from xml.etree.ElementTree import parse, iterparse

filename = 'top.xml'

def recipe1():
    '''步骤都变得相当的繁琐'''
    doc = parse(filename)
    print(f"{doc.findtext('author') = }")
    print(f"{doc.find('content') = }")
    print(f"{doc.find('content/html') = }")
    print(f"{doc.find('content/{http://www.w3.org/1999/xhtml}html') = }")
    print(f"{doc.findtext('content/{http://www.w3.org/1999/xhtml}html/head/title') = }")
    print(f"{doc.findtext('content/{http://www.w3.org/1999/xhtml}html/{http://www.w3.org/1999/xhtml}head/{http://www.w3.org/1999/xhtml}title') = }")

def recipe2():
    doc = parse(filename)
    ns = XMLNamespaces(html='http://www.w3.org/1999/xhtml')
    print(f"{doc.find(ns('content/{html}html')) = }")
    print(f"{doc.findtext(ns('content/{html}html/{html}head/{html}title')) = }")

def recipe3():
    for evt, elem in iterparse('top.xml', ('end', 'start-ns', 'end-ns')):
        print(f"{evt, elem = }")

    print(f"{elem = }") # This is the topmost element

class XMLNamespaces:
    def __init__(self, **kwargs):
        self.namespaces = {}
        for name, uri in kwargs.items():
            self.register(name, uri)
    
    def register(self, name, uri):
        self.namespaces[name] = '{'+uri+'}'

    def __call__(self, path):
        return path.format_map(self.namespaces)

def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()

if __name__ == '__main__':
    main()     